package com.itheima.health.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.health.constant.RedisConstant;
import com.itheima.health.dao.SetmealDao;
import com.itheima.health.entity.PageResult;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.JedisPool;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CheckItemServiceImpl
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/8/20 16:00
 * @Version V1.0
 */
// dubbo（整合声明式事务处理1：配置applicationContext-tx.xml对类代理，2：@Service(interfaceClass = CheckItemService.class)）
@Service(interfaceClass = SetmealService.class)
@Transactional
public class SetmealServiceImpl implements SetmealService {

    @Autowired
    SetmealDao setmealDao;

    @Autowired
    JedisPool jedisPool;

    @Override
    public void add(Setmeal setmeal, Integer[] checkgroupIds) {
        // 1：新增套餐
        setmealDao.add(setmeal);
        // 2：向套餐和检查组的中间表中插入数据
        setSetMealAndCheckGroup(setmeal.getId(),checkgroupIds);

        // 在Service类将图片名称存放redis中（保存数据库的时候），使用集合
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
    }

    @Override
    public PageResult findPage(String queryString, Integer currentPage, Integer pageSize) {
        // 分页插件
        PageHelper.startPage(currentPage,pageSize);
        List<Setmeal> list = setmealDao.findPage(queryString);
        PageInfo<Setmeal> pageInfo = new PageInfo<>(list);
        return new PageResult(pageInfo.getTotal(),pageInfo.getList());
    }

    @Override
    public List<Setmeal> findAll() {
        return setmealDao.findAll();
    }

    @Override
    public Setmeal findById(Integer id) {
        return setmealDao.findById(id);
    }

    // 统计套餐预约人数占比（饼图）
    @Override
    public List<Map<String, Object>> findSetmealCountByOrder() {
        return setmealDao.findSetmealCountByOrder();
    }

    // 向套餐和检查组的中间表中插入数据
    private void setSetMealAndCheckGroup(Integer id, Integer[] checkgroupIds) {
        if(checkgroupIds!=null && checkgroupIds.length>0){
            for (Integer checkgroupId : checkgroupIds) {
                Map<String,Object> map = new HashMap<>();
                map.put("checkgroupId",checkgroupId);
                map.put("setmealId",id);
                setmealDao.addSetMealAndCheckGroup(map);
            }
        }
    }
}
